<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
    <link rel="stylesheet" href="./stylesheets/style.css">
    <script src="./js/fileinput.min.js"></script>
    <script src="./js/fileinput_locale_zh.js"></script>
    <script src="./js/jquery.bootstrap.min.js"></script>
    <link href="./stylesheets/fileinput.min.css" rel="stylesheet" type="text/css"/>
    <!-- Angular-->
    <script src="http://cdn.bootcss.com/angular.js/1.4.0-rc.1/angular.min.js"></script>
    <title>Snack Bar</title>
    <style type="text/css">

      .modal.msg-popup .modal-body {
        color: #000;
      }

      .modal.msg-popup .modal-content {
        border-color: green;
        background-color: #e3ffff;
      }

    </style>
</head>
<body ng-controller="myCtrl">

<div class="navbar-wrapper">
      <div class="container">

        <nav class="navbar navbar-inverse navbar-fixed-top">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="/" ng-click = "getAll();">Snack Bar</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                <li><a href="/" ng-click = "getAll();">首页</a></li>
                <li><a href="/messages">留言</a></li>
                <li><a href="/tallybook">欠账本</a></li>
                <li><a href="/contact">关于</a></li>
                <li class="active"><a href="/insert">管理员</a></li>
              </ul>
            </div>
          </div>
        </nav>
      </div>
</div>

<div class="container snackcontainer">
<div class="messageform">
    <form name="form">
      <h1 class="showMoreSnack">零食管理处</h1>
      <table class="table">
        <tr>
          <td>
            <div class="form-inline">
                <label for="name">零食名称:</label>
                <input type="text" class="form-control" ng-model="name" id="name" placeholder="零食名称">
                <span ng-class="{true:'alert alert-danger',false:'alert alert-success'}[isNameExist]" ng-show="isNameExist">零食名称已存在！</span>
            </div>
          </td>
        </tr>
        <tr>
          <td>
            <div class="form-inline">
              <label for="snackpic">上传图片:</label>
                <input id="snackpic" type="file" class="file" fileread="snackpic" data-show-upload="false"/>
            </div>
          </td>
        </tr>
        <tr>
          <td>
            <div class="form-inline">
              <label for="price">价格:</label>
              <input type="number" name="price" class="form-control" ng-min="0.1" ng-model="price" id="price" placeholder="零食价格">
              <label for="category">种类:</label>
              <select class="form-control" ng-init="category==category||items[0].category" ng-model="category" id="category" ng-options="item.category as item.display for item in items">
              </select>
              <span class="alert alert-danger well-sm" ng-show="form.price.$error.min">金额不能小于等于零！</span>
              <span ng-class="{true:'alert alert-danger',false:'alert alert-success'}[isPriceEmpty]" ng-show="isPriceEmpty">请输入正确的金额信息！</span>
            </div>
          </td>
        </tr>
        <tr>
          <td>
            <div class="form-inline">
              <label for="description">描述:</label>
              <input type="text" class="form-control" ng-model="description" id="description" placeholder="商品描述">
              <label for="address">位置:</label>
              <input type="text" class="form-control" ng-model="address" id="address" placeholder="零食位置">
            </div>
          </td>
        </tr>
        <tr>
          <td>
            <button type="submit" class="btn btn-primary submitButton" ng-click="save(name);">保存</button>
            <span ng-class="{true:'alert alert-danger',false:'alert alert-success'}[isEmpty]" ng-show="isEmpty">请填完全部信息！</span>
          </td>
        </tr>
      </table>  
    </form>
</div>

<br/>

<div class="row">
  <div class="col-xs-6 col-sm-4 col-md-12">
    <table class="table table-hover">
         <tr> 
          <th>零食名称</th>
          <th>价格</th>
          <th>零食位置</th>
          <th>操作</th>
        </tr>
        <tr ng-repeat="i in messageList">
          <td>
            {{i.name}}
          </td>
          <td>
            ￥{{i.price}}
          </td>
          <td>
            {{i.address}}
          </td>
          <td>
            <button type="submit" class="btn btn-danger" ng-click="delete(i);">删除</button>
          </td>
        </tr>
    </table>
</div>
</div>
</div>
<script>

    var app=angular.module("app",[], function () {
        console.log('started to get message');
    });
/*     var fileDirective=angular.module("fileDirective",[], function () {
        console.log('started file directive');
    }); */
    app.directive("fileread", [function () {
	    return {
	        scope: {
	            fileread: "="
	        },
	        link: function (scope, element, attributes) {
	            element.bind("change", function (changeEvent) {
	                scope.$apply(function () {
	                	var file = changeEvent.target.files[0];
	                	var reader = new FileReader();
	                	reader.readAsArrayBuffer(file);
	                	reader.onload = function loaded(evt) {
							var binaryString = new Uint8Array(evt.target.result);
							scope.fileread = binaryString;
						};
	                });
	            });
	        }
	    }
	}]);
    app.factory('formDataObject', function() {
    	return function(data) {
	    	var fd = new FormData();
	    	angular.forEach(data, function(value, key) {
	    		fd.append(key, value);
	    	});
	    	return fd;
	    	};
    	});
    app.controller("myCtrl",function($scope,$http,formDataObject){
      $scope.items = [
        {display: '小吃', category:'小吃'},
        {display: '饮料', category:'饮料'},
        {display: '其它', category:'其它'}
      ];
      
      $http.get("/api/snack").success(function(response){
        $scope.messageList = response;
      });
      
	  $scope.insert = function(){
		  var picture = $scope.snackpic;
      if(!$scope.nullOrEmpty($scope)){
        $scope.isPriceEmpty = !$scope.price? true:false;
        if(!$scope.isPriceEmpty){
          $http({
              method  : 'post',
              url     : '/api/snack',
            /* headers: {
                'Content-Type': 'multipart/form-data'
                }, */
            /*   headers: {
                  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }, */
              data: {
                 loves : 0,
                 description : $scope.description,
                 category : $scope.category,
                 price : $scope.price,
                 address : $scope.address,
                 name : $scope.name,
                 pic: $scope.snackpic
                },
                //file:$scope.snackpic
       // transformRequest: formDataObject
          }) 
            .success(function(data) {
              $.messager.popup("保存成功！");
                $http.get("/api/snack").success(function(response){
                  $scope.messageList = response;
                });
            })
        }  
      }
     };

    $scope.delete = function(record){
            $http({
                  method  : 'delete',
                  url     : '/api/snack/' + record._id,
              })
                .success(function(data) {
                    $http.get("/api/snack").success(function(response){
                      $scope.messageList = response;
                    });
                    
                })
              };

      $scope.save = function(keyword){
      $http.get("/api/snack/search/"+keyword).success(function(response){
          $scope.tasklist = response;
          $scope.isNameExist = false;
          $scope.isPriceEmpty = false;
          $scope.isEmpty = false;
          if($scope.tasklist.length>0){
            $scope.isNameExist=true; 
          }else{
            $scope.isNameExist=false; 
            $scope.insert();
          }
        });
    };
    
    $scope.nullOrEmpty = function(record){
       if(!record.description || !record.address ||  !record.category || !record.name || !record.snackpic){
          $scope.isEmpty = true;
       }else{
         $scope.isEmpty = false;
       }
       return $scope.isEmpty;
    };
});
</script>

<!-- FOOTER -->
<footer class="footer">
  <p>&copy; 2015 Company, Inc. &middot; Powered By &middot; <a href="https://nodejs.org/">Nodejs</a></p>
</footer>

<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="http://cdn.bootcss.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

</body>
</html>